package com.rop.znyx.user.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rop.znyx.common.auth.AuthContextHolder;
import com.rop.znyx.common.constant.RedisConstant;
import com.rop.znyx.common.exception.BizException;
import com.rop.znyx.common.result.Result;
import com.rop.znyx.common.result.ResultCodeEnum;
import com.rop.znyx.enums.UserType;
import com.rop.znyx.model.user.User;
import com.rop.znyx.user.service.UserService;
import com.rop.znyx.user.util.HttpClientUtil;
import com.rop.znyx.user.util.WXConstantPropertiesUtil;
import com.rop.znyx.util.JwtHelper;
import com.rop.znyx.vo.user.LeaderAddressVo;
import com.rop.znyx.vo.user.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA
 * User: Rop
 * Date: 2023/7/18
 * Time: 13:09
 * Description:
 */

@Api(tags = "微信管理")
@RestController
@RequestMapping("api/user/weixin")
@RequiredArgsConstructor
public class WeiXinApiController {

    private final UserService userService;

    private final RedisTemplate<Object, Object> redisTemplate;

    /**
     * 用户微信授权登录
     * code: 临时票据
     */
    @ApiOperation("用户微信授权登录")
    @GetMapping("wxLogin/{code}")
    public Result<Map<String, Object>> login(@PathVariable("code") String code) {
        // 1.得到微信返回code临时票据值

        // 2.拿着code + 小程序id + 小程序密钥  请求微信接口服务
        String wxOpenAppId = WXConstantPropertiesUtil.WX_OPEN_APP_ID;
        String wxOpenAppSecret = WXConstantPropertiesUtil.WX_OPEN_APP_SECRET;

        // 使用HttpClient工具请求
        // get请求，拼接请求地址 + 参数
        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String urlToken = String.format(url.toString(), wxOpenAppId, wxOpenAppSecret, code);

        String result = null;
        try {
            result = HttpClientUtil.get(urlToken);
        } catch (Exception e) {
            BizException.error(ResultCodeEnum.FETCH_ACCESS_TOKEN_FAILED);
        }

        // 3.请求微信接口服务，返回两个值， session_key 和 openid(微信的唯一标识)
        JSONObject jsonObject = JSONObject.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openid");

        // 4.添加微信用户信息到数据库中  user表
        // 判断是否是第一次使用微信授权登录：如何判断？(根据openId进行判断)
        User user = userService.getBaseMapper().selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, openId));
        if (ObjectUtil.isNull(user)) {
            user = new User();
            user.setOpenId(openId);
            user.setNickName(openId);
            user.setPhotoUrl("");
            user.setUserType(UserType.USER);
            user.setIsNew(0);
            userService.save(user);
        }

        // 5.根据userId查询当前用户的提货点和团长的信息
        // 提货点：user_delivery表
        // 团长：leader表
        LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId());

        // 6.使用JwtHelper根据userId和username生成token字符串
        String token = JwtHelper.createToken(user.getId(), user.getNickName());

        // 7.获取当前登录用户的信息，放到redis中进行使用，设置有效时间
        UserLoginVo userLoginVo = this.userService.getUserLoginVo(user.getId());
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + user.getId(), userLoginVo, RedisConstant.USER_KEY_TIMEOUT, TimeUnit.DAYS);

        // 8.需要的数据封装到map中进行返回
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("leaderAddressVo", leaderAddressVo);
        map.put("token", token);

        return Result.ok(map);
    }

    @PostMapping("/auth/updateUser")
    @ApiOperation(value = "更新用户昵称与头像")
    public Result<Void> updateUser(@RequestBody User user) {
        User user1 = userService.getById(AuthContextHolder.getUserId());
        //把昵称更新为微信用户
        user1.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
        user1.setPhotoUrl(user.getPhotoUrl());
        userService.updateById(user1);
        return Result.ok(null);
    }
}
